package com.eric.springboot.service.impl;

import com.eric.springboot.config.security.JwtUserDetails;
import com.eric.springboot.config.security.UserDetailsServiceImpl;
import com.eric.springboot.dao.UserMapper;
import com.eric.springboot.dao.UserRoleMapper;
import com.eric.springboot.entity.User;
import com.eric.springboot.entity.UserLoginRequest;
import com.eric.springboot.entity.UserRole;
import com.eric.springboot.service.UserService;
import com.eric.springboot.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Eric
 * @date 2021.2.3
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public String login(UserLoginRequest userLoginRequest) {
        JwtUserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(userLoginRequest.getUserName());
        if (!passwordEncoder.matches(userLoginRequest.getPassword(), userDetails.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        return jwtTokenUtil.generateToken(userDetails);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserLoginRequest userLoginRequest) {
        User user = new User()
                .setUserName(userLoginRequest.getUserName())
                .setPassword(passwordEncoder.encode(userLoginRequest.getPassword()))
                .setNickName(userLoginRequest.getUserName());
        //新增用户信息
        userMapper.insert(user);
        UserRole userRole = new UserRole()
                .setUserId(user.getId())
                .setRoleId(2L);
        //为用户指定角色
        userRoleMapper.insert(userRole);
    }

}
